﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;
using SharingCenter.Web.Classes;
using SharingCenter.Web.Classes.Message;

namespace SharingCenter.Web.Account
{
    public partial class ResetPassword : PageBase
    {
        protected string email = string.Empty;
        protected void Page_Init(object sender, EventArgs e)
        {
            Wizard1.ActiveStepChanged += new EventHandler(Wizard1_ActiveStepChanged);
            
        }

        void Wizard1_ActiveStepChanged(object sender, EventArgs e)
        {
            switch (Wizard1.ActiveStep.Title)
            {
                case "SendPassword":
                    email = txtEmail.Text.Trim().ToLower();

                    if (!ValidateionCode1.IsValid)
                    {
                        Wizard1.ActiveStepIndex = 0;
                        msgError.Text = "验证码有误。";
                        msgError.Visible = true;
                    }
                    else
                    {
                        MembershipUser user = Membership.GetUser(email);
                        
                        if (user == null || !user.IsApproved || user.IsLockedOut)
                        {
                            msgError.Text = email + "不存在或已被禁用。";
                            msgError.Visible = true;
                            Wizard1.ActiveStepIndex = 0;
                        }
                        else
                        {
                            SendPassword(ref user);
                        }
                    }
                   
                    break;
            }
        }

        private void SendPassword(ref MembershipUser u)
        {
            //string newPwd = Membership.GeneratePassword(8, 1);
            
            string newPassword = u.ResetPassword();
            Dictionary<string, string> rep = new Dictionary<string, string>();
            rep.Add("NewPassword", newPassword);
            rep.Add("UserName", email);
            rep.Add("NickName", Profile.Personal.NickName);

            if (!MailOperations.SendSystemMail("Account", "ResetPassword", email, rep))
            {
                SetTopMostMessage("邮件发送错误", true);
                RefreshPage();
            }
            else
            {
                //Membership.UpdateUser(u);
                WebProfile p = WebProfile.GetProfile(u.UserName);
                p.Security.PasswordReset = true;
                p.Save();
            }
        }
    }
}
